package com.cmcc.aregister.cs.util;

import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.util.HashMap;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;

public class DrawableManager {
	private static HashMap<String, SoftReference<Drawable>> drawableMap = new HashMap<String, SoftReference<Drawable>>();

	public DrawableManager() {
	}

	public static Drawable fetchDrawable(String urlString) {
		SoftReference<Drawable> drawableRef = drawableMap.get(urlString);
		if (drawableRef != null) {
			Drawable drawable = drawableRef.get();
			if (drawable != null)
				return drawable;

			drawableMap.remove(urlString);
		}

		try {
			InputStream is = null;
			HttpURLConnection c = null;
			c = Utils.getHttpConnection(urlString);
			c.connect();
			is = c.getInputStream();
			Drawable drawable = Drawable.createFromStream(is, "src");
			drawableRef = new SoftReference<Drawable>(drawable);
			drawableMap.put(urlString, drawableRef);
			return drawableRef.get();
		} catch (MalformedURLException e) {
			return null;
		} catch (IOException e) {
			return null;
		}
	}

	public static void fetchDrawableOnThread(final String urlString,
			final ImageView imageView) {
		SoftReference<Drawable> drawableRef = drawableMap.get(urlString);
		if (drawableRef != null) {
			Drawable drawable = drawableRef.get();
			if (drawable != null) {
				imageView.setImageDrawable(drawableRef.get());
				return;
			}
			// Reference has expired so remove the key from drawableMap
			drawableMap.remove(urlString);
		}

		final Handler handler = new Handler() {
			@Override
			public void handleMessage(Message message) {
				imageView.setImageDrawable((Drawable) message.obj);
			}
		};

		Thread thread = new Thread() {
			@Override
			public void run() {
				// TODO : set imageView to a "pending" image
				Drawable drawable = fetchDrawable(urlString);
				Message message = handler.obtainMessage(1, drawable);
				handler.sendMessage(message);
			}
		};
		thread.start();
	}

}
